<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 
 * Class AdminGrid
 * @author Mrdang
 *
 */
class AdminGrid{
	var $CI; // CodeIgniter super object
	var $columns; // column data
	var $rows_per_page; // how many rows of data to show per page?
	var $params; // parameters for the data call
	var $params_default;
	var $filters; // data model parameters set by the user's filters
	var $limit; //limit
	var $offset; // database offset
	var $data; // data array
	var $data_model; // model to retrieve data from
	var $data_function; // method to retrieve data from within the model
	var $total_rows; // these are how many rows are in the total dataset, either calculated automatically or given by total_rows()
	var $pagination; // stores the HTML for pagination links
	var $sort_column;
	var $sort_dir;
	var $title;
	var $buttons;
	var $_curPage = 1;
	var $grid_id;
	var $row_action;
	var $actions;
	var $mass_key;
	
    function __construct() {
    	$this->CI =& get_instance();
        $this->rows_per_page = '20';
    }
    
    /**
    * Set Datasource
    *
    * Sets the model and method to retrieve the data from
    *
    * @param string $data_model The model
    * @param string $data_function The method
    * @param array $data_filters Default filters to pass to the get_X() method (default: none)
    *
    * @return boolean TRUE
    */
    function datasource ($data_model, $data_function, $data_filters = array()) {
    	$this->data_model = $data_model;
    	$this->data_function = $data_function;
    	$this->params_default = $data_filters;
    }
    
    function set_grid_id($grid_id){
    	$this->grid_id = $grid_id;
    	return $this;
    }
    
    function set_mass_key($key){
    	$this->mass_key = $key;
    	return $this;
    }
    
    function get_mass_key(){
    	return $this->mass_key;
    }
    
    function get_grid_id(){
    	if (is_null($this->grid_id)){
    		$this->grid_id = $this->CI->router->fetch_method();
    	}
    	return $this->grid_id;
    }
    /**
    * Total Rows
    *
    * Set total rows so we don't have to try and fish it from the method with a double call
    *
    * @param int $total_rows
    *
    * @return boolean TRUE;
    */
    function total_rows ($total_rows) {
    	$this->total_rows = $total_rows;
    	return TRUE;
    }
    
    /**
    * Add Action
    *
    * Adds an action button the dataset
    * When clicked, it creates an ASCII'd, base64_encoded, serialized array of all ID's in the checkboxes of the dataset
    *
    * @param string $name The name of the action for the button
    * @param string $link The link (e.g. /customers/delete) to pass the variable to (e.g. /customers/delete/39f32432849340923849234)
    *
    * @return bool TRUE upon success
    */
    function add_mass_action($actionId,array $action) {
    	$this->actions[$actionId] = $action;
    	return TRUE;
    }
    
    function mass_action_to_json(){
    	$result = array();
    	if (is_array($this->actions) && count($this->actions) > 0) {
	    	foreach ($this->actions as $actionId=>$action){
	    		$action['id']=$actionId;
	    		$result[$actionId] = $action;
	    	}
    	}
    	return jsonEncode($result);
    }
    
    function mass_action_to_html(){
    		$return = '';
    		if (is_array($this->actions) && count($this->actions) > 0){
		    	$return .='<div class="right">';
		    	$return .='<div class="entry-edit">';
				$return .='<form id="'. $this->CI->router->fetch_method().'Grid_massaction-form" method="post" action="">';
				$return .='<div><input type="hidden" value="'.$this->CI->security->get_csrf_hash().'" name="'.$this->CI->security->get_csrf_token_name().'"></div>';
				$return .='<fieldset>';
				$return .='<span class="field-row">';
				$return .='<label>Actions</label> ';
	    		$return .='<select id="'. $this->CI->router->fetch_method().'Grid_massaction-select" class="required-entry select absolute-advice local-validation">';
	    		$return .='<option value=""></option>';
	    			foreach ($this->actions as $actionId=>$action){
	    				$return .= '<option value="' .$actionId. '" ><span>'.$action['label'].'</span></option>';
	    			}
	    		
	    		$return .='</select>';
	    		$return .='</span>';
	    		$return .='<span class="outer-span" id="'.$this->get_grid_id().'Grid_massaction-form-hiddens"></span>';
	            $return .='<span class="outer-span" id="'.$this->get_grid_id().'Grid_massaction-form-additional"></span>';
				$return .='<span class="field-row">';
				$return .='<button class="scalable " style="" type="button" onclick="'.$this->get_grid_id().'Grid_massactionJsObject.apply()">';
				$return .='<span>Gửi đi</span>';
				$return .='</button>';
				$return .='</span>';
				$return .='</fieldset>';
				$return .='</form>';
		    	$return .='</div>';
		    	$return .='<div class="no-display">';
		    		foreach ($this->actions as $actionId=>$action){
		    			$return .='<div id="'.$this->get_grid_id().'Grid_massaction-item-'.$actionId.'-block"></div>';
		    		}
		    	$return .='</div>';
		    	$return .='</div>';
    		}
    		return $return;
    }
	function add_button($name, $link,$class='') {
		$this->buttons[] = array(
									'name' => $name,
									'link' => $link,
									'class'=>$class
								);
	}
	function get_button () {
		if (is_null($this->buttons)) {
			return '';
		}
		$return ='';
		if (is_array($this->buttons)){
			foreach ($this->buttons as $link) {
				$return .= '<button type="button" class="button '.$link['class'].'" onclick="setLocation(\'' . $link['link'] . '\')">'."\n".'<span>' . $link['name'] . '</span>'."\n".'</button>'."\n";
			}
		}
		return $return;
	}
    /**
    * Set Rows Per Page
    *
    * How many rows to show per page?
    *
    * @param int $rows_per_page
    *
    * @return boolean TRUE;
    */
    function rows_per_page($rows_per_page) {
    	$this->rows_per_page = $rows_per_page;
    	return $this;
    }
    
    function set_row_action($action){
    	$this->row_action = $action;
    	return $this;
    }
    
    function get_row_action(){
    	if (!is_null($this->row_action) || $this->row_action !=''){
    		return $this->row_action;
    	}
    	return false;
    	
    }
    
    function set_title($title){
    	$this->title = $title;
    	return true;
    }
    
    function get_grid_url($method="",$params = array()){
    	if ($method == ""){
    		$method = $this->CI->router->fetch_method();
    	}
    	return admin_url($this->CI->router->fetch_module().'/'.$this->CI->router->fetch_class().'/'.trim($method,'/'),$params);
    }
    /**
    * Get Filter Array
    *
    * Return the filter URL segment as an array of filters
    *
    * @return array or FALSE if it doesn't exist
    */
    function get_filter_array() {
    	if (($filter = $this->CI->input->get('filter',false))){
	    	$values = explode('&',base64_decode($filter));
	    	$serialize = array();
	    	//var_dump($values);
			foreach ($values as $value) {
				list($name,$value) = explode('=',$value);
				if ($value != '') {
					$this->filters[$name] = $value;
				}	
			}
    	}
    	else {
    		$this->filters = FALSE;
    	}
//		if (is_array($this->filters) && count($this->filters) > 1)) {
//			foreach ($this->filters as $key => $value) {
//				$this->set_filters[$key] = urldecode($value);
//			}
//		}
		return $this->filters;
    }
    
    /**
    * Get Limit
    *
    * Get the database limit
    *
    * @return int Limit
    */
    function get_limit () {
    	if (($limit = $this->CI->input->get('limit',false))) {
    		$this->limit = $limit;
    		$this->rows_per_page($limit);
    	}
    	else {
    		$this->limit = $this->rows_per_page;	
    	}
    	
    	return $this->limit;
    }
    
    /**
    * Get Offset
    *
    * Are we browsing a page other than page #1?  If so, we have an offset.
    *
    * @return int Offset
    */
    function get_offset() {
    	if (($page = $this->CI->input->get('page',false))) {
    		$this->offset = (int) ($page-1)*$this->rows_per_page;
    	}
    	else {
    		$this->offset = 0;
    	}
    	
    	return $this->offset;
    }
	
 	function get_parameters () {
    	$params = $this->params;
    	
    	if (isset($params['limit'])) {
    		unset($params['limit']);
    	}
    	
    	if (isset($params['offset'])) {
    		unset($params['offset']);
    	}
    	
    	return $params;
    }
    
    function initialize () {
    	// get filter values
		$this->get_filter_array();
		
		// begin data getting process with an empty parameters array for the model's get_X() method
    	$this->params = array();
    	
    	// limit to the rows_per_page configuration
    	$this->params['limit'] = $this->get_limit();
    	
    	// calculate offset
    	$this->params['offset'] = $this->get_offset();
    	
    	$this->params_filters = array();
    	
    	if ($this->CI->input->get('sort')) {
    		$this->sort_column = $this->CI->input->get('sort');
    		$this->sort_dir = $this->CI->input->get('dir');
    		$this->params_filters['sort'] = $this->sort_column;
    		$this->params_filters['dir'] = $this->sort_dir;
    	}
    	
    	
    	
    	foreach ($this->columns as $column) {
    		if ($column['filters'] == TRUE) {
    			if (($column['type'] == 'select' or $column['type']=='publish' or $column['type'] == 'text' or $column['type'] == 'id') and isset($this->filters[$column['filter_name']])) {
    				$this->params_filters[$column['filter_name']] = $this->filters[$column['filter_name']];
    			}
    			elseif ($column['type'] == 'date' and (isset($this->filters[$column['filter_name'] . '_from']) or isset($this->filters[$column['filter_name'] . '_to']))) {
    				$this->params_filters[$column['filter_name'].'_from'] =  (empty($this->set_filters[$column['filter_name'] . '_from']))?'':$this->filters[$column['filter_name'].'_from'];
    				$this->params_filters[$column['filter_name'].'_to'] = (empty($this->set_filters[$column['filter_name'] . '_end']))?'':$this->filters[$column['filter_name'].'_to'];
    			}
    		}
    	}
    	reset($this->columns);
    	
    	// for the major data call, we need to combine database parameters, default parameters, and parameters
    	// created by the filters
    	$this->params = array_merge($this->params, $this->params_filters, $this->params_default);
    	
    	// get data with our $this->params
    	$this->CI->load->model($this->data_model,'data_model');
    	
    	$data_function = $this->data_function;
 //   	$this->CI->data_model->$data_function($this->params);
    	//do sort db
    	if (!is_null($this->sort_column) && !is_null($this->sort_dir)){
    		$this->CI->data_model->db->order_by($this->sort_column,$this->sort_dir);
    	}

    	//do filter db
    	if (($filter = $this->get_filter_array())){
    		foreach ($filter as $key=>$value){
    			$this->CI->data_model->db->having($key,$value);
    		}
    	}
  //  	var_dump((string) $this->CI->data_model->db->last_query());
    	if ($this->get_limit()){
    		$this->CI->data_model->db->limit($this->get_limit(),$this->get_offset());
    	}
    	
    	//paper
    	//if (!is_null($this->))
    	
    	// do a CSV export?
    	if ($this->CI->input->get('export') == 'csv') {
    		// get data without limits
    		$unlimited_params = $this->get_parameters();
    		$this->data = $this->CI->data_model->$data_function($unlimited_params);
    		//$this->data = $this->CI->data_model->$data_function($this->params);
    		
    		// convert to CSV
			$this->CI->load->library('array_to_csv');
			$this->CI->array_to_csv->input($this->data);
			
			header("Content-type: application/vnd.ms-excel");
  			header("Content-disposition: attachment; filename=export-" . $this->data_function . '-' . date("Y-m-d") . ".csv");
			echo $this->CI->array_to_csv->output();
			die();
    	}
    	
		// get data with our parameters
		$this->data = $this->CI->data_model->$data_function($this->params);
		$this->total_rows = $this->CI->data_model->$data_function($this->get_parameters(),true);
		
		return TRUE; 
    }
        
    /**
    * Define visible Dataset columns
    *
    * Defines the columns with width, sort, filtering, name
    *
    * @param array $columns The columns
    *
    * @return void
    */
    function columns ($columns = array()) {
	    foreach ($columns as $column) {
	    	$this->columns[] = array(
	    					'name' => $column['name'],
	    					'sort_column' => isset($column['sort_column']) ? $column['sort_column'] : FALSE,
	    					'width' => isset($column['width']) ? $column['width'] : 'auto',
	    					'type' => isset($column['type']) ? $column['type'] : FALSE,
	    					'filters' => (!isset($column['filter']) || ($column['filter'] == false)) ? FALSE : TRUE,
	    					'filter_name' => (!isset($column['filter'])) ? FALSE : $column['filter'],
	    					'options' => isset($column['options']) ? $column['options'] : array(),
	    					'index'=>isset($column['index'])? $column['index']:'',
	    					'action'=>isset($column['action'])?$column['action']:''
	    				);		
	    	if (isset($column['type']) and $column['type'] == 'link' and !isset($column['action']) ) {
	    		die(show_error('Unable to create a "link" filter without action.'));
	    	}
	    	if (isset($column['type']) and $column['type'] == 'select' and !isset($column['options'])) {
	    		die(show_error('Unable to create a "select" filter without options.'));
	    	}	
    	}
    	reset($this->columns);
    	
    	return;
    }
    
    /**
    * Output Table Head
    *
    * Returns the header of the table, including pagination/buttons bar, and form beginning
    *
    * @return string HTML output
    */
    function table_head () {
    	$output = '';
    	$output .= '<table id="'. $this->CI->router->fetch_method().'Grid_table" class="dataGrid" cellpadding="0" cellspacing="0">'."\n";
    	$output .= '<thead>'."\n".'<tr class="headings">'."\n";
    	$output .= '<th >'."\n".'<span class="nobr"></span>'."\n".'</th>'."\n";
    	$i=0;
    	while (list($key,$column) = each($this->columns)) {
    		if (!empty($column['sort_column'])) {
    			$class='not-sort';
    			$title = 'desc';
    			if ($this->CI->input->get('sort') == $column['index']){
					if ($this->CI->input->get('dir')=='asc'){
	    				$title = 'desc';
	    				$class = 'sort-arrow-asc';
	    			}else{
	    				$title = 'asc';
	    				$class = 'sort-arrow-desc';
	    			}
    			}
    			$column['name'] = '<a class="'.$class.'" title="'.$title.'" name="' . $column['index'] . '" href="javascript:void(0)"><span class="sort-title">' . $column['name'] . '</span></a>';
	    	}
   			$output .= '<th style="width:' . $column['width'] . '" '.((empty($column['sort_column']) || $column['sort_column'] == false)?'class="no-link '.((($i+1)==count($this->columns))?' last':'').'"':'').'>'."\n".'<span class="nobr">' . $column['name'] . '</span>'."\n".'</th>'."\n";
    		$i++;
    	}
    	reset($this->columns);
    	
    	$output .= '</tr>'."\n";
    	
    		$output .= '<tr class="filter">'."\n";
	    	$output .= '<th style="width:2%" class="a-center">'."\n".'<span class="nobr"> </span></th>'."\n";
	    	
    		while (list(,$column) = each($this->columns)) {
				if ($column['filters'] == TRUE) {
					$output .= '<th>'."\n";
					
					if ($column['type'] == 'text' || $column['type'] == 'link' || $column['type'] == 'money') {
						$value = (isset($this->filters[$column['filter_name']])) ? $this->filters[$column['filter_name']] : '';
						$output .= '<input id="'. $this->CI->router->fetch_method().'Grid_'.$this->CI->router->fetch_method().'_filter_' . $column['filter_name'] . '" type="text" class="input-text" name="' . $column['filter_name'] . '" value="' . $value . '" />';
					}
					elseif ($column['type'] == 'id') {
						$value = (isset($this->filters[$column['filter_name']])) ? $this->filters[$column['filter_name']] : '';
						$output .= '<input id="'. $this->CI->router->fetch_method().'Grid_'.$this->CI->router->fetch_method().'_filter_' . $column['filter_name'] . '" type="text" class="input-text id" name="' . $column['filter_name'] . '" value="' . $value . '" />';
					}
					elseif ($column['type'] == 'date') {
						$value = (isset($this->filters[$column['filter_name'] . '_from'])) ? $this->filters[$column['filter_name'] . '_from'] : '';
						$classes = 'datepicker';
						$output .='<div class="range">';
						$output .= '<div class="range-line date"><span class="label">Từ : </span><input id="" type="text"  class="' . $classes . ' input-text" name="' . $column['filter_name'] . '_from"  value="' . $value . '" /></div>';
						$value = (isset($this->filters[$column['filter_name'] . '_to'])) ? $this->filters[$column['filter_name'] . '_to'] : '';
						$output .= '<div class="range-line date"><span class="label">Đến :</span><input id="" type="text" class="' . $classes . ' input-text" name="' . $column['filter_name'] . '_to" value="' . $value . '" /></div>';
						$output .='</div>';
					}
					elseif ($column['type'] == 'select' || $column['type']=='publish') {
						$output .= '<select id="'. $this->CI->router->fetch_method().'Grid_'.$this->CI->router->fetch_method().'_filter_' . $column['filter_name'] . '" name="' . $column['filter_name'] . '">'."\n".'<option value=""></option>'."\n";
						
						foreach ($column['options'] as $value => $name) {
							$selected = (isset($this->filters[$column['filter_name']]) and $this->filters[$column['filter_name']] == $value) ? ' selected="selected"' : '';
							$output .= '<option value="' . $value . '"' . $selected . '>' . $name . '</option>'."\n";
						}
						
						$output .= '</select>'."\n";
					}
					
					$output .= "\n".'</th>'."\n";
				}
				else {
					$output .= '<th>'."\n".'<span class="nobr"> </span></th>'."\n";
				}
    		}
    		
    		$output .= '</tr>'."\n".'</thead>'."\n".'<tbody>'."\n";
    	
    	return $output;
    }
    
    function table_close () {
    	$output = '</tbody>'."\n".'</table>'."\n";
    	
    	return $output;
    }
    private function selected($value){
    	return $selected = ($value == $this->get_limit())?'selected="selected"':'';
    }
    
    private function get_jsobject($mass_key=''){
    	$js = "";
    	$js .= $this->get_grid_id()."JsObject = new varienGrid('".$this->get_grid_id()."Grid','".$this->get_grid_url()."', 'page', 'sort', 'dir','filter'); \n";
    	$js .= $this->get_grid_id()."JsObject.useAjax = '1';\n";
    	$js .= $this->get_grid_id()."JsObject.rowClickCallback = openGridRow;\n";
    	$js .= "var {$this->get_grid_id()}Grid_massactionJsObject = new varienGridMassaction('{$this->get_grid_id()}Grid_massaction', {$this->get_grid_id()}JsObject, '', 'internal_{$mass_key}', '{$mass_key}'); \n";
    	$js .= $this->get_grid_id()."Grid_massactionJsObject.setItems({$this->mass_action_to_json()})\n";
    	//$js .= $this->get_grid_id()."Grid_massactionJsObject.setGridIds('1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24');\n";
    	//$js .= $this->get_grid_id()."Grid_massactionJsObject.setUseSelectAll(true);\n";
    	$js .= $this->get_grid_id()."Grid_massactionJsObject.errorText = 'Please select items.'; \n";
    	return jsScript($js);
    }
    public function display(){
    	$this->initialize();
    	$datagrid = '';
    	if (!$this->CI->input->is_ajax()){
	    	$datagrid .='<div class="content-header">'."\n";
			$datagrid .='<table cellspacing="0">'."\n";
			$datagrid .='<tbody>'."\n";
			$datagrid .='<tr>'."\n";
			$datagrid .='<td style="width:50%;">'."\n";
			$datagrid .='<h3 class="icon-head">'.$this->title.'</h3>'."\n";
			$datagrid .='</td>'."\n";
			$datagrid .='<td class="a-right">'."\n";
			$datagrid .=$this->get_button();
			$datagrid .='</td>'."\n";
			$datagrid .='</tr>'."\n";
			$datagrid .='</tbody>'."\n";
			$datagrid .='</table>'."\n";
			$datagrid .='</div>'."\n";
	    	$datagrid .='<div>'."\n";
	    	$datagrid .='<div id="'. $this->CI->router->fetch_method().'Grid">'."\n";
    	}
    	$datagrid .='<table class="actions" cellpadding="0" cellspacing="0">'."\n";
    	$datagrid .='<tbody>'."\n";
    	$datagrid .='<tr>'."\n";
    	$datagrid .='<td class="pager">'."\n";
		$datagrid .=__('Page').' ';
		$_totalPage = ceil((int)$this->total_rows/$this->limit);
		if ($_totalPage > 1){
			$this->_curPage = ($this->CI->input->get('page')=='')?$this->_curPage:$this->CI->input->get('page');
		}
		if ($this->_curPage > 1){
			$datagrid .='<a href="javascript:void(0)" onclick="'.$this->get_grid_id().'JsObject.setPage(\''.($this->_curPage-1).'\');return false;" title="Trang trước"><img class="arrow" alt="Đến trang trước" src="'.base_url('templates/backend/images/pager_arrow_left.gif').'"></a>';
		}else{
			$datagrid .='<img class="arrow" alt="Đến trang trước" src="'.base_url('templates/backend/images/pager_arrow_left_off.gif').'">';
		}
		$datagrid .=' <input type="text" name="page" value="'.$this->_curPage.'" class="input-text page" onkeypress=""/>';
    	if ($this->_curPage < $_totalPage){
			$datagrid .='<a href="javascript:void(0)" onclick="'.$this->get_grid_id().'JsObject.setPage(\''.($this->_curPage+1).'\');return false;" title="Trang sau"><img class="arrow" alt="Đến trang sau" src="'.base_url('templates/backend/images/pager_arrow_right.gif').'"></a>';
		}else{
			$datagrid .='<img class="arrow" alt="Đến trang sau" src="'.base_url('templates/backend/images/pager_arrow_right_off.gif').'">';
		}
		$datagrid .=' '.__('of').' '.$_totalPage.' '.__('pages');
		$datagrid .='<span class="separator">|</span>';
    	$datagrid .=' '.__('View').' ';
    	$datagrid .='<select onchange="'.$this->get_grid_id().'JsObject.loadByElement(this);" name="limit">';
		$datagrid .='<option value="20" '.$this->selected('20').' >20</option>';
		$datagrid .='<option value="30" '.$this->selected('30').'>30</option>';
		$datagrid .='<option value="50" '.$this->selected('50').'>50</option>';
		$datagrid .='<option value="100" '.$this->selected('100').'>100</option>';
		$datagrid .='<option value="200" '.$this->selected('200').'>200</option>';
		$datagrid .='</select>';
		$datagrid .=' '.__('per page');
    	$datagrid .='<span class="separator">|</span>';
    	$datagrid .=__('Total').' '.$this->total_rows.' '.__('records found');
    	$datagrid .='</td>';
		$datagrid .='<td class="export a-right">';
    	$datagrid .='<img class="v-middle" alt="" src="'.base_url('templates/backend/images/icon_export.gif').'">';
    	$datagrid .=' In: ';
    	$datagrid .='<select id="Grid_export" style="width:8em;" name="export">';
    	$datagrid .='<option value=""></option>';
    	$datagrid .='<option value="csv">CSV</option>';
    	$datagrid .='</select>';
    	$datagrid .='<button id="id_'.random_string('numeric','16').'" class="scalable task" type="button"><span>Xuất file</span></button>';
		$datagrid .='</td>';
		$datagrid .='<td class="filter-actions a-right">';
    	$datagrid .= '<button type="button" onclick="'.$this->get_grid_id().'JsObject.doFilter()"  class="dofilter" name="dofilter" /><span>Tìm kiếm</span></button><button id="resetFilters" type="button" onclick="'.$this->get_grid_id().'JsObject.resetFilter()" name="resetFilters" class="button" /><span>Làm lại</span></button>';
		$datagrid .='</td>';
		$datagrid .='</tr>'."\n";
    	$datagrid .='</tbody>'."\n";
    	$datagrid .='</table>'."\n";
    	
    	$datagrid .='<div id="'. $this->CI->router->fetch_method().'Grid_massaction">'."\n";
    	$datagrid .='<table class="massaction" cellspacing="0" cellpadding="0">'."\n";
    	$datagrid .='<tbody>';
    	$datagrid .='<tr>';
    	$datagrid .='<td>';
    	$datagrid .='<a href="javascript:void(0)" onclick="return '.$this->get_grid_id().'Grid_massactionJsObject.selectAll()">'.__('Select All').'</a>';
        $datagrid .='<span class="separator">|</span>';
        $datagrid .='<a href="javascript:void(0)" onclick="return '.$this->get_grid_id().'Grid_massactionJsObject.unselectAll()">'.__('Unselect All').'</a>';
        //$datagrid .='<span class="separator">|</span>';
        //$datagrid .='<a href="javascript:void(0)" onclick="return '.$this->get_grid_id().'Grid_massactionJsObject.selectVisible()">'.__('Select Visible').'</a>';
        //$datagrid .='<span class="separator">|</span>';
        //$datagrid .='<a href="javascript:void(0)" onclick="return '.$this->get_grid_id().'Grid_massactionJsObject.unselectVisible()">'.__('Unselect Visible').'</a>';
        $datagrid .='<span class="separator">|</span>';
        $datagrid .='<strong id="'.$this->get_grid_id().'Grid_massaction-count">0</strong> '.__('items selected');
    	$datagrid .='</td>';
    	$datagrid .='<td>'."\n";
		$datagrid .= $this->mass_action_to_html();
    	$datagrid .='</td>'."\n";
    	$datagrid .='</tr>'."\n";
    	$datagrid .='</tbody>'."\n";
    	$datagrid .='</table>'."\n";
    	$datagrid .='</div>'."\n";
    	
    	$datagrid .='<div class="grid">'."\n";
    	$datagrid .='<div class="hor-scroll">'."\n";
    	$datagrid .= $this->table_head();
    	if (!empty($this->data)){
    		$i = 0;
    		foreach ($this->data as $row){
    			foreach ($this->columns as $column){
    				if ($column['type']=='id'){
    					$this->set_mass_key($column['index']);
    					$entrity = $column['index'];
    				}
    				break;
    			}
    			if (empty($entrity) || !isset($entrity)){
    				die(show_error('You must create column type ID .'));
    			}
    			$datagrid .='<tr class="pointer" '.(($this->get_row_action())?'title="'.$this->get_grid_url($this->get_row_action(),array('id'=>$row[$entrity])).'"':'').' >'."\n";
    			$datagrid .='<td class="a-center">'."\n".'<input class="massaction-checkbox" type="checkbox" value="'.$row[$entrity].'" name="'.$this->get_mass_key().'"></td>'."\n";
    				$i=0;	
    				foreach ($this->columns as $column){
    					$last = (($i+1)==count($this->columns))?'class="last"':'';
    					if ($column['type']=='link'){
    						$datagrid .='<td '.$last.'><a href="'.$column['action'].'">'.$row[$column['index']].'</a></td>'."\n";
    					}elseif ($column['index']==''){
    						$datagrid .='<td  '.$last.'></td>'."\n";
    					}elseif ($column['type']=='money'){
    						$datagrid .='<td  '.$last.'>'.$row[$column['index']].' '.setting('symbol').'</td>'."\n";
    					
    					}elseif ($column['type']=='publish'){
    						$img = ($row[$column['index']]=='1')?'rule_component_apply.gif':'rule_component_remove.gif';
    						$title = ($row[$column['index']]=='1')?'Tắt':'Bật';
    						$value = ($row[$column['index']]=='1')?'0':'1';
    						$datagrid .='<td align="center"  '.$last.'><a id="publish_'.$row[$entrity].'" onclick="Publish(\''.$this->get_grid_url($column['action']).'\',\''.$row[$entrity].'\',\''.$value.'\');" title="'.$title.'" href="javascript:void(0);"><img src = "'.base_url('templates/backend/images').'/'.$img.'"></a>';
    					}else{
    						$data = ($column['index']=='')?'':$row[$column['index']];
    						$datagrid .='<td  '.$last.'>'.$data.'</td>'."\n";
    					}
    					$i++;
    				}
    			$datagrid .="\n".'</tr>'."\n";
    		}
    	}
    	$datagrid .= $this->table_close();
    	$datagrid .='</div>'."\n";
    	$datagrid .='</div>'."\n";
    	if (!$this->CI->input->is_ajax()){
	    	$datagrid .='</div>'."\n";
	    	$datagrid .='</div>'."\n";
	    	$datagrid .= $this->get_jsobject($this->get_mass_key());
    	}
    	return $datagrid;
    }
    
}